package com.kl.component.exception;

import com.alibaba.fastjson.JSON;
import com.kl.common.exception.SystemException;
import com.kl.modular.common.response.ResponseBase;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeoutException;

/**
 * 全局异常处理
 *
 * 主要处理非运行时异常与自定义异常
 *
 * @author xr_zjb
 * @author 2017/06/07 11:17
 *
 * 
 */
public class ResolverException implements HandlerExceptionResolver {

	private static final Logger logger = LoggerFactory.getLogger(ResolverException.class);

	private static boolean isAjaxRequest(HttpServletRequest request) {
		String requestedWith = request.getHeader("X-Requested-With");
		return StringUtils.equals(requestedWith, "XMLHttpRequest");
	}

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		logger.info("全局异常处理ERROR:", ex);
		ModelAndView model = new ModelAndView("error/500.jsp");
		ResponseBase reBase = new ResponseBase();
		// 判断异常类型
		if (ex instanceof SystemException) {
			// 自定义抛出异常
			logger.error("------统一异常拦截：自定义异常 " + ex.toString());
			SystemException xrProEx = (SystemException) ex;
			logger.info("errorMsg: " + xrProEx.getErrorMsg());
			reBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
			reBase.setMsg(xrProEx.getErrorMsg());
			model.addObject("errorMsg", xrProEx.getErrorMsg());
		} else if (ex instanceof TimeoutException) {
			// 请求超时
			logger.error("------统一异常拦截：请求超时 " + ex.toString());
			reBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
			reBase.setMsg("请求超时");
		} else if(ex instanceof UnauthorizedException || ex instanceof AuthorizationException){
			// shiro 没有访问权限 有可能是非法访问
			logger.error("------统一异常拦截：没有权限访问该资源 " + ex.toString());
			reBase.setStatus(ResponseBase.RESPONSE_STATUS_FAILED);
			reBase.setMsg("没有权限访问该资源");
			model = new ModelAndView("../unauthorized.jsp");
		}else {
			logger.error("------统一异常拦截：系统繁忙" + ex.toString());
			ex.printStackTrace();
			reBase.setStatus(ResponseBase.RESPONSE_STATUS_ERROR);
			reBase.setMsg("系统繁忙");
		}
		// 判断请求类型
		if (isAjaxRequest(request)) {
			// Ajax请求
			String jsonStr = JSON.toJSONString(reBase);
			//response.setContentType("application/json");
			response.setContentType("text/json");
			response.setCharacterEncoding("UTF-8"); // 定义编码
			try {
				PrintWriter writer = response.getWriter();
				writer.write(jsonStr);
				writer.flush();
				writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}
		return model;
	}

}
